<template>
  <div class="studying-box">
    <NewCard :title="`${selectRadioList.roleName}学习-${selectStudyItem.examName}`" :isright="true">
        <template slot="right">
            <p class="scoreNum"><span>{{getScore()}}</span>分</p>
        </template>

        <!-- 关闭页面 -->
        <div class="closePage" v-if="isClose">
            <img src="~@/assets/images/wjg_img@2x.png" alt="">
            <p>无操作超过{{selectStudyItem.minutes}}分钟，本次学习已自动结束</p>
            <el-button round class="againOne" @click="relearnBtn">重新学习</el-button>
            <el-button round @click="viewResults">查看结果</el-button>
        </div>

        <!-- 当前题目 -->
        <div class="currentTitle" v-else>
            <div class="currentQ-box" v-if="questionList.length">
                <!-- 题目 -->
                <h3>{{currentTitle+1}}. {{questionList[currentTitle].question}}</h3>
                <!-- 选项 -->
                <el-checkbox-group v-model="checked" v-if="!questionList[currentTitle].answerStringArray">
                    <el-checkbox v-for="(item,key,index) in questionList[currentTitle].options" :key="index" :label="key" :disabled="getCheckdisa()">{{getKeyEn((index+1).toString())}}、{{item}}</el-checkbox>
                </el-checkbox-group>
                <!-- 回答过后的渲染 -->
                <el-checkbox-group v-model="checked" v-else>
                    <el-checkbox v-for="(item,key,index) in questionList[currentTitle].chaoOptions" :key="index" :label="key" :disabled="getCheckdisa()">{{getKeyEn((index+1).toString())}}、{{item}}</el-checkbox>
                </el-checkbox-group>

                <!-- 答题解析 -->
                <div class="analysis-box" v-if="questionList[currentTitle]&&questionList[currentTitle].answerStringArray">
                    <p class="answer">
                        正确答案：
                        <span class="correct">{{sortKeyEn(questionList[currentTitle].correctAnswer)}}</span> 
                        您的答案：
                        <span class="errorA" :class="questionList[currentTitle].result=='1'?'correct':''">{{sortKeyEn(questionList[currentTitle].userAnswer)}}</span>
                    </p>
                    <div class="analysis">
                        参考解析：{{questionList[currentTitle].analysis}}
                    </div>
                </div>

                <!-- 提示 -->
                <div class="hint-box" v-else>
                    <div class="hintTem" v-if="questionList[currentTitle].tips">
                        <svg-icon icon-class="tishi_icon"/>
                        <div v-html="questionList[currentTitle].tips"></div>
                    </div>
                </div>

            </div>

            <!-- 按钮 -->
            <div class="affirmBtn">
                <SubBtn>
                    <template slot="btn">
                        <p>共{{questionList.length}}题，已答对<span>{{correctQuesNum}}</span>题</p>
                        <el-button round v-if="questionList[currentTitle]&&questionList[currentTitle].answerStringArray" @click="clickNext">{{getNextBtntxt()}}</el-button>
                        <el-button round v-else v-show="checked.length" @click="clickSubmit">确认</el-button>
                    </template>
                </SubBtn>
            </div>
        </div>
    </NewCard>
  </div>
</template>

<script>
import NewCard from "@/wss/components/newCard.vue";
import SubBtn from "@/components/subBtn/subBtn.vue";
//防抖：debounce 用户触发事件过于频繁，只要最后一次事件的操作
import debounce from "lodash/debounce";

import {getQuestionListNoAnswerByExamApi,getQuestionGetResultApi,submitExamResultApi} from "@/BMViews/api/assess/question.js"
export default {
    name: 'studying',
    components:{NewCard,SubBtn},
    props:{
        // 选择的一个科目
        selectStudyItem:{
            type: Object,
        },
        // 选择的一个角色
        selectRadioList:{
            type: Object,
        },
    },
    data(){
        return{
            isClose: false,//关闭时长到的时候显示关闭页面
            currentTitle: 0,//从第一题开始
            questionList: [],//不包含答案的题目列表
            checked:[],//当前题目所选
            correctQuesNum: 0,//已答对的题目数量
            testUser:'',
            isHmClose: false,//是手动结束
        }
    },
    mounted(){
        this.getQuestionListNoAnswerByExam() // 根据examId 获取题目列表,不包含答案
        this.pageNoHandle(this.selectStudyItem.minutes)
        
        // 关闭超时界面
        this.$bus.$on('showStudying',()=>{
            this.isClose = false
        })
    },
    beforeDestroy(){
        // 解绑$bus
        this.$bus.$off('showStudying')
        // 手动点击结束的时候这里不用发请求结束
        if(!this.isHmClose){
            this.autoSubmitExamResult() //离开页面结束考试
        }
        clearInterval(this.testUser); //清除定时器
    },
    watch:{
        'selectStudyItem.id':{
            handler(newVal,oldVal){
                this.getQuestionListNoAnswerByExam() // 根据examId 获取题目列表,不包含答案
            },
        },
    },
    methods:{
        // 根据examId 获取题目列表,不包含答案
        async getQuestionListNoAnswerByExam(){
            let examResultId = this.selectStudyItem.id
            let result = await getQuestionListNoAnswerByExamApi({examResultId})
            if(result.code==200){
                this.questionList = JSON.parse(JSON.stringify(result.rows))
            }
        },

        // 获取题目答题结果
        async getQuestionGetResult(){
            let checkList = JSON.parse(JSON.stringify(this.checked))
            // 去除已选的下划线
            let answerArr = []
            checkList.forEach(item=>{
                answerArr.push(item.slice(1))
            })
            let myAnswer = answerArr.join(',') //整合逗号拼接
            //乱序的答案
            let chaoOptions = JSON.parse(JSON.stringify(this.questionList[this.currentTitle].options))
            
            let params = {
                quesId: this.questionList[this.currentTitle].id, //问题的id
                examResultId: this.selectStudyItem.id, //科目id
                answer: myAnswer,//我的回答
                no: this.currentTitle+1,//题号
            }
            let result = await getQuestionGetResultApi(params)
            if(result.code==200){
                this.$set(this.questionList, this.currentTitle, result.data)
                this.$set(this.questionList[this.currentTitle], 'chaoOptions', chaoOptions) //把乱序的答案存一下
                this.$set(this.questionList[this.currentTitle], 'myAnswer', myAnswer) //放进我的答案
                this.correctQuesNum = result.data.quesYes //获取答对的题目
            }
        },

        // 点击确认按钮
        clickSubmit: debounce(function(){
            this.getQuestionGetResult() //获取题目答题结果
        },500),

        // 判断当前选项是否能点击
        getCheckdisa(){
            if(this.questionList[this.currentTitle]&&this.questionList[this.currentTitle].answerStringArray){
                return true
            }else{
                return false
            }
        },

        // 把数字转成英文字母
        getKeyEn(key){
            if(!key) return
            let arr = key.split(',')
            let newArr = arr.sort((a, b) => Number(a)- Number(b))
            let alphabet = ''
            newArr.forEach(item => {
                alphabet = alphabet + String.fromCharCode(64 + parseInt(item));
            });
            return alphabet
        },

        // 给字母排序
        sortKeyEn(answer){
            let arr = answer.split('')
            let newArr = arr.sort()
            return newArr.join('')
        },

        // 获取得分
        getScore(){
            let scpreArr = this.questionList.filter(item=>{
                return item.result == '1'
            })
            return parseInt((scpreArr.length/this.questionList.length)*100) || 0
        },

        // 最后一题按钮名字
        getNextBtntxt(){
            if(this.currentTitle+1 == this.questionList.length){
                return '结束考试'
            }else{
                return '我已理解，下一题'
            }
        },

        // 点击下一题
        clickNext: debounce(function(){
            // 是最后一题的话要结束考试
            if(this.currentTitle+1 == this.questionList.length){
                this.isHmClose = true // 是手动结束考试
                this.submitExamResult() // 结束考试
                return
            }
            this.checked = []// 清空已选的答案
            this.currentTitle = this.currentTitle + 1
        },500),

        // 结束考试
        async submitExamResult(){
            let data = {
                id: this.selectStudyItem.id,
                examId: this.selectStudyItem.examId,
                userQa: []
            }
            this.questionList.forEach(item=>{
                let obj = {
                    q: item.id,
                    a: item.myAnswer,
                }
                data.userQa.push(obj)
                // this.$set(data.qa,key,item.myAnswer) //添加键值对 id：答案
            })
            let result = await submitExamResultApi(data)
            if(result.code==200){
                this.$bus.$emit('endOfTheTest',this.selectStudyItem)
            }
        },

        // 自动结束考试
        async autoSubmitExamResult(){
            let data = {
                id: this.selectStudyItem.id,
                examId: this.selectStudyItem.examId,
                userQa: []
            }
            this.questionList.forEach(item=>{
                if(item.myAnswer){
                    let obj = {
                        q: item.id,
                        a: item.myAnswer,
                    }
                    data.userQa.push(obj)
                    // this.$set(data.qa,key,item.myAnswer) //添加键值对 id：答案
                }
            })
            let result = await submitExamResultApi(data)
            if(result.code==200){
            }
        },

        // 页面无操作的时候自动关闭考试
        pageNoHandle(minutes){
            let that = this
            // 页面无操作
            let funObj = {
                timeUserFun:'timeUserFun',
            }
            funObj.timeUserFun = function(time){
                var time = time || 2;    // 默认参数
                var userTime = time*60;
                var objTime = {
                    init:0,
                    time:function(){
                        objTime.init += 1;
                        if(objTime.init == userTime){
                            // 用户到达未操作事件 做一些处理
                            that.autoSubmitExamResult() //结束考试
                            that.isClose = true
                            console.log('无操作自动关闭');
                            clearInterval(that.testUser);
                        }
                    },
                    eventFun:function(){
                        clearInterval(that.testUser);
                        objTime.init = 0;
                        that.testUser = setInterval(objTime.time,1000);
                    }
                }
    
                that.testUser = setInterval(objTime.time,1000);
    
                var body = document.querySelector('html');
                body.addEventListener("click",objTime.eventFun);
                body.addEventListener("keydown",objTime.eventFun);
                body.addEventListener("mousemove",objTime.eventFun);
                body.addEventListener("mousewheel",objTime.eventFun);
            }
            funObj.timeUserFun(minutes) //单位分钟
        },

        // 点击重新学习
        async relearnBtn(){
            clearInterval(this.testUser);
            this.correctQuesNum = 0
            this.currentTitle = 0
            await this.getQuestionListNoAnswerByExam()
            this.$bus.$emit('clickStartBus',this.selectStudyItem)
        },

        // 点击查看结果按钮
        viewResults(){
            clearInterval(this.testUser);
            this.$bus.$emit('endOfTheTest',this.selectStudyItem)
        },
    },
}
</script>

<style lang="scss" scoped>
ul,p,h3,h4 {
  list-style: none;
  margin: 0;
  padding: 0;
}
.currentTitle{
    margin-bottom: 60px;
}
// 得分
.scoreNum{
    color: #fff;
    background-color: #39486F;
    border-radius: 30px 0 0 30px;
    padding: 8px 25px;
    margin: 0;
    font-size: 14px;
    margin-right: -30px;
    span{
        font-size: 18px;
        margin-right: 5px;
    }
}

// 当前题目
.currentTitle{
    margin-top: 20px;
    h3{
        font-size: 20px;
        color: #333333;
        line-height: 28px;
    }
    .el-checkbox-group{
        margin-top: 20px;
        .el-checkbox{
            width: 100%;
            margin: 15px 0;
        }
    }
}

// 提示
.hint-box{
    background-color: #F6F7FA;
    margin-top: 50px;
    .hintTem{
        display: flex;
        flex-wrap: wrap;
        padding: 10px 10px;
    }
    svg{
        font-size: 16px;
        margin-right: 5px;
    }
    div{
        width: calc(100% - 21px);
        color: #999;
        font-size: 12px;
    }
}
::v-deep .hint-box div p{
    margin: 0;
    line-height: 24px;
}

// 解析
.analysis-box{
    .answer{
        background-color: #F6F7FA;
        padding: 6px 20px;
        font-size: 12px;
        color: #333333;
        margin: 10px 0;
        span{
            margin-right: 20px;
        }
        .errorA{
            color: #EB564E;
        }
        .correct{
            color: #4ABD62;
        }
    }
    .analysis{
        font-size: 14px;
        color: #666666;
        line-height: 28px;
    }
}

// 按钮
.affirmBtn{
    .subBtn{
        justify-content: space-between;
        align-items: center;
        padding: 10px 30px;
        p{
            min-height: 36px;
            line-height: 36px;
            font-size: 14px;
            color: #333333;
            span{
                color: #F87A23;
                margin: 0 5px;
            }
        }
        .el-button{
            width: auto;
            min-width: 100px;
            padding: 10px 15px;
            border-color: #F87A23;
            background-color: #F87A23;
            color: #fff;
        }
        
    }
}

// 关闭页面
.closePage{
    text-align: center;
    margin-top: 50px;
    img{
        width: 30%;
    }
    p{
        font-size: 16px;
        color: #333333;
        margin: 30px 0;
    }
    .el-button{
        display: block;
        margin: 0 auto;
        padding: 8px 30px;
        font-size: 14px;
        border-color: #F87A23;
        color: #F87A23;
        margin-bottom: 20px;
    }
    .againOne{
        border-color: #F87A23;
        background-color: #F87A23;
        color: #fff;  
    }
}
</style>
<style scoped>
.currentTitle .el-checkbox.is-checked >>> .el-checkbox__label{
    color: #666;
}
.currentTitle .el-checkbox.is-checked.is-disabled >>> .el-checkbox__label{
    color: #C0C4CC;
}
.currentTitle .el-checkbox >>> .is-checked .el-checkbox__inner {
    background-color: #39486F;
    border-color: #39486F;
}
.currentTitle .el-checkbox >>> .is-checked.is-disabled .el-checkbox__inner {
    opacity: 0.6;
}
</style>